package com.sky.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl extends ServiceImpl<OrderMapper, Orders> implements ReportService {


    @Resource
    private OrderMapper orderMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkspaceService workspaceService;
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDates = new ArrayList<>();
        ArrayList turnoverList = new ArrayList();
        //第一天
        localDates.add(begin);
        //其他天数
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            localDates.add(begin);
        }
        //查询一天的已完成订单的钱
        for (LocalDate localDate : localDates) {
            LocalDateTime min = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(localDate, LocalTime.MAX);
            HashMap hashMap = new HashMap();
            hashMap.put("begin",min);
            hashMap.put("end",max);
            hashMap.put("status",Orders.COMPLETED);
            BigDecimal amounts = orderMapper.sumByMap(hashMap)==null?new BigDecimal(0.0):orderMapper.sumByMap(hashMap);
            turnoverList.add(amounts);
        }
        //将日期的集合转成字符串
        String dateList = StringUtils.join(localDates, ",");
        //将金额转成字符串
        String turnover = StringUtils.join(turnoverList, ",");
        return TurnoverReportVO.builder()
                .dateList(dateList)
                .turnoverList(turnover)
                .build();
    }

    /**
     * 统计用户总数量和新增用户数量
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> localDates = new ArrayList<>();
        //添加第一天
        localDates.add(begin);
        //添加第二天等等
        while (!begin.equals(end)){
             begin = begin.plusDays(1);
             localDates.add(begin);
        }
        String dateList = StringUtils.join(localDates, ",");
        //封装totalUserList和newUserList
        ArrayList<Integer> totalUserList = new ArrayList<>();
        ArrayList<Integer> newUserList = new ArrayList<>();
        for (LocalDate localDate : localDates) {
            LocalDateTime min = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(localDate, LocalTime.MAX);
            HashMap hashMap = new HashMap();
            hashMap.put("end",max);
            //查询总的用户
            Integer users = userMapper.countByUser(hashMap);
            totalUserList.add(users);
            hashMap.put("begin",min);
            //查询一天的新用户
            Integer newUsers = userMapper.countByUser(hashMap);
            newUserList.add(newUsers);
        }
        String total = StringUtils.join(totalUserList, ",");
        String newUser = StringUtils.join(newUserList, ",");
        return UserReportVO.builder()
                .dateList(dateList)
                .totalUserList(total)
                .newUserList(newUser)
                .build();
    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> localDates = new ArrayList<>();
        //添加第一天
        localDates.add(begin);
        //添加第二天等等
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            localDates.add(begin);
        }
        String dateList = StringUtils.join(localDates, ",");
        //封装每日的总数和有效订单数
        ArrayList<Integer> orderCountList = new ArrayList<>();
        ArrayList<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate localDate : localDates) {
            LocalDateTime min = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(localDate, LocalTime.MAX);
            HashMap hashMap = new HashMap();
            hashMap.put("begin",min);
            hashMap.put("end",max);
            //查询总的订单数
            Integer orderTotal = orderMapper.countOrder(hashMap);
            orderCountList.add(orderTotal);
           hashMap.put("status",Orders.COMPLETED);
            Integer validOrder = orderMapper.countOrder(hashMap);
            validOrderCountList.add(validOrder);
        }
        String orderCount = StringUtils.join(orderCountList, ",");
        String validOrderCount = StringUtils.join(validOrderCountList, ",");
        //计算时间内总的订单数
        Integer totalCount = orderCountList.stream().reduce(Integer::sum).get();
        //计算时间内总的有效订单数
        Integer validCount = validOrderCountList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate=0.0;
        if (totalCount!=0){
            orderCompletionRate=validCount.doubleValue()/totalCount;
        }

        return OrderReportVO.builder()
                .orderCountList(orderCount)
                .validOrderCountList(validOrderCount)
                .totalOrderCount(totalCount)
                .orderCompletionRate(orderCompletionRate)
                .validOrderCount(validCount)
                .dateList(dateList)
                .build();
    }

    @Override
    public SalesTop10ReportVO countTop10(LocalDate begin, LocalDate end) {
        LocalDateTime min = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime max = LocalDateTime.of(end, LocalTime.MAX);
        HashMap hashMap = new HashMap();
        hashMap.put("begin",min);
        hashMap.put("end",max);
        List<GoodsSalesDTO> goodsSalesDTO = orderDetailMapper.countTop10(hashMap);
        List<String> names = goodsSalesDTO.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = goodsSalesDTO.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String  nameList= StringUtils.join(names, ",");
        String numberList = StringUtils.join(numbers, ",");
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1. 查询数据库，获取营业数据---查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
